import axios from 'axios';
import qs from 'qs';
import {notification} from 'ant-design-vue';

// 拦截request,设置全局请求为ajax请求
axios.interceptors.request.use((config) => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest';
    return config;
});

let isExpireSession = false;

function isEmptyObject(e) {
    for (let t in e) {
        return !1;
    }
    return !0;
}

const treatParam = function(param) {
    if (!param.url) throw new Error('缺失ajax必要参数url');

    let p = {};

    p.fail = function(err) {
        // 处理404错误
        if(err.response && err.response.status == 404) {
            // Notice.error({title: '访问页面异常', desc: '您访问的页面不存在'});
            throw err;
        }

        if (err.response && err.response.data) {
            let retData = err.response.data;
            if (isExpireSession) {
                return;
            }
            if (retData.code == 803) {
                isExpireSession = true;
            }

            notification['error']({
                message: retData.msg,
                description: isEmptyObject(retData.data) ? '' : JSON.stringify(retData.data),
            });
        } else {
            // Notice.error({title: '报文解析异常', desc: err.message});
        }

        throw err;
    };
    return p;
};

const get = async function(param) {
    let p = treatParam(param);

    try {
        let res = await axios({
            method: 'get',
            url: param.url,
            params: param.data,
        });

        return res.data;
    } catch (e) {
        p.fail(e);
    }
};

const post = async function(param) {
    let p = treatParam(param);
    if (!param.contentType) {
        param.contentType = index.CONTENT_TYPE_FORMDATA;
    }

    let data;
    if (param.contentType == index.CONTENT_TYPE_FORMDATA) {
        data = qs.stringify(param.data);
    } else {
        data = param.data;
    }

    try {
        let res = await axios({
            method: 'post',
            url: param.url,
            data: data,
            headers: { 'Content-Type': param.contentType },
        });

        return res.data;
    } catch (e) {
        p.fail(e);
    }
};

const index = {
    get: get,
    post: post,
    CONTENT_TYPE_FORMDATA: 'application/x-www-form-urlencoded;charset=UTF-8',
    CONTENT_TYPE_JSON: 'application/json;charset=UTF-8',
    SUCCESS: 0,
    FAIL: 1,
};

export default index;
